import { useReducer } from "react";

export const UseReducerDemo = () => {
  const initialState = {name: 'Tom', age: 18}
  const reducer = (preState, action) => {
    const {type, payload} = action
    switch(type) {
      case 'addAge':
        return {...preState, age: preState.age+1}
      case 'subAge':
        return {...preState, age: preState.age-1}
      case 'changePerson':
        return {...payload}
      default:
        return preState
    }
  }
  const [state, dispatch] = useReducer(reducer, initialState)

  return (
    <>
      <h1>useReducer的使用</h1>
      <p>姓名: {state.name}, 年龄: {state.age}</p>
      <button onClick={() => dispatch({type:'addAge'})} >添加年龄</button>
      <button onClick={() => dispatch({type: 'subAge'})}>减小年龄</button>
      <button onClick={() => dispatch( { type:'changePerson', payload:{name: '夏天', age: 27}})}>换人了</button>
    </>
  )
}
